<script setup lang="jsx">
import { xsToOpts } from '@/util/index.js';
import { computed, onMounted, ref, watch } from 'vue';

const selectCompo = ref();
const props = defineProps(['visible', 'loading', 'classes']);
const emit = defineEmits(['update:visible', 'cancel', 'ok']);
const visible = ref(props.visible);
watch(visible, newVal => emit('update:visible', newVal));

const searchValue = ref('');
const selected = ref('');
const filterOption = (input, opt) => opt.value.includes(input);
const options = computed(() => xsToOpts(props.classes));

// autofocus 没用
onMounted(() => selectCompo.value.focus());

function onCancel(event) {
  emit('cancel');
  visible.value = false;
}

function onOk(event) {
  emit('ok', selected.value);
}
</script>

<template>
  <a-modal
    class="label-selector"
    :visible="visible"
    title="选择标签"
    centered
    :mask="false"
    :mask-closable="false"
    :closable="false"
    @cancel="onCancel">

    <!-- mode="multiple" -->
    <!-- :max-tag-count="3" -->
    <!-- :max-tag-text-length="6" -->
    <a-select
      ref="selectCompo"
      v-model:value="selected"
      :options="options"
      :search-value="searchValue"
      :filter-option="filterOption"
      open
      show-search
      placeholder="请选择标签"
      allow-clear
      :getPopupContainer="triggerNode => (triggerNode.parentNode)"
      style="width: 100%;"
      :dropdown-style="{
        'position': 'relative',
        'height': '266px',
        'border': '1px solid rgb(228,228,228)',
        'border-radius': '6px',
        'box-shadow': 'none'
      }"
      @search="value => (searchValue = value)"
    >
      <template #option="{ label }">
        <div
          @dblclick="() => {
            selected = label;
            onOk();
          }"
        >
          {{ label }}
        </div>
      </template>
    </a-select>

    <template #footer>
      <a-button @click="onCancel">取消</a-button>
      <a-button type="primary" :disabled="!selected" @click="onOk">确定</a-button>
    </template>
  </a-modal>
</template>

<style>
.label-selector .ant-modal-header,
.label-selector .ant-modal-body { padding: 10px; }

.label-selector .ant-modal-title {
  font-size: 14px;
  line-height: 1;
}

/* getPopupContainer 对应节点大概率是 modal-body 的末子元素 */
.label-selector .ant-select-selector ~ div:last-child { position: static !important; }

/* 因需要双击选择，故区域要大 */
.label-selector .ant-select-item { padding: 0; }
.label-selector .ant-select-item > div { padding: 5px 12px }
</style>
